package com.moli.iov.base.remote.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.moli.iov.base.cache.mongodb.AlarmEquipmentRecordService;
import com.moli.iov.base.cache.mongodb.TerminalInstallLogsService;
import com.moli.iov.base.cache.mongodb.VehicleRegisterRecordService;
import com.moli.iov.base.cache.mongodb.VehicleSimChangeRecordService;
import com.moli.iov.base.constants.DictConstants;
import com.moli.iov.base.constants.SysConstants;
import com.moli.iov.base.enums.AlarmTypeEnum;
import com.moli.iov.base.enums.AuditResultsEnum;
import com.moli.iov.base.enums.AuditStatusEnum;
import com.moli.iov.base.enums.AuthorizedEnum;
import com.moli.iov.base.enums.AuthorizedSourceEnum;
import com.moli.iov.base.enums.HandlingStatusEnum;
import com.moli.iov.base.enums.OnLineStatusEnum;
import com.moli.iov.base.enums.YesOrNoEnum;
import com.moli.iov.base.model.dto.req.QueryVehicleTboxListParamDto;
import com.moli.iov.base.model.dto.req.TerminalBindingDeleteDto;
import com.moli.iov.base.model.dto.req.TerminalBindingSaveDto;
import com.moli.iov.base.model.dto.req.VehicleBaseReqDto;
import com.moli.iov.base.model.dto.req.VehicleTboxReqDto;
import com.moli.iov.base.model.dto.req.VehicleTboxUpdateReqDto;
import com.moli.iov.base.model.dto.res.VehicleBaseTboxResDto;
import com.moli.iov.base.model.dto.res.VehicleTboxBindingResDto;
import com.moli.iov.base.model.dto.res.VehicleTboxResDto;
import com.moli.iov.base.model.mongo.AlarmEquipmentRecord;
import com.moli.iov.base.model.mongo.TerminalInstallLogs;
import com.moli.iov.base.model.mongo.VehicleRegisterRecord;
import com.moli.iov.base.model.mongo.VehicleSimChangeRecord;
import com.moli.iov.base.model.po.DictData;
import com.moli.iov.base.model.po.TerminalInstallationAudit;
import com.moli.iov.base.model.po.VehicleBase;
import com.moli.iov.base.model.po.VehicleTbox;
import com.moli.iov.base.remote.IVehicleTboxRemoteService;
import com.moli.iov.base.service.IDictDataService;
import com.moli.iov.base.service.ITerminalInstallationAuditService;
import com.moli.iov.base.service.IVehicleBaseService;
import com.moli.iov.base.service.IVehicleTboxService;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.base.util.ServiceValidation;
import com.moli.iov.enums.UserTypeEnum;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.handle.alarm.enums.AlarmCodeEnum;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.notify.enums.MessageTypeEnum;
import com.moli.iov.notify.model.dto.NoticeMessageCenterDto;
import com.moli.iov.notify.remote.INoticeMessageCenterRemoteService;
import com.moli.iov.real.service.IRealService;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.JsonUtils;
import com.moli.iov.util.SnowflakeUtils;
import com.moli.iov.util.ValidationUtils;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author whl
 */

@Service(group = "${service.group}")
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class IVehicleTboxRemoteServiceImpl implements IVehicleTboxRemoteService {
    @Autowired
    private TerminalInstallLogsService logsService;
    @Autowired
    private IVehicleTboxService iVehicleTboxService;
    @Autowired
    private IVehicleBaseService iVehicleBaseService;
    @Autowired
    private AlarmEquipmentRecordService iAlarmEquipmentRecordService;
    @Autowired
    private IDictDataService dictDataService;
    @Autowired
    private VehicleSimChangeRecordService recordService;
    @Autowired
    private VehicleRegisterRecordService vehicleRegisterRecordService;
    @Autowired
    private ITerminalInstallationAuditService iTerminalInstallationAuditService;

    @Reference(group = "${service.group}", check = false)
    private INoticeMessageCenterRemoteService noticeMessageCenterRemoteService;

    @Reference(group = "${service.group}", check = false)
    private IRealService iRealService;

    /**
     * 用于网关注册
     */
    @Override
    public RestResponse gatewayRegisterVehicleTbox(VehicleTboxReqDto vehicleTboxReqDto) {
        log.info("网关注册tbox入参：" + vehicleTboxReqDto);
        // 1 车联  不存在  添加   报警   未授权车辆
        // 2 车联  不存在  添加   报警   未授权车辆
        log.info("注册VehicleTboxReqDto:{}" + vehicleTboxReqDto);
        if (vehicleTboxReqDto == null || StringUtils.isBlank(vehicleTboxReqDto.getDeviceId())
                || StringUtils.isBlank(vehicleTboxReqDto.getVin())) {
            return RestResponse.failure("参数为null");
        }
        VehicleTbox oldVehicleTbox = iVehicleTboxService
                .getVehicleTboxByDeviceId(vehicleTboxReqDto.getDeviceId());
        VehicleBase oldVehicleBase = iVehicleBaseService
                .getVehicleBaseUnauthorizedByVin(vehicleTboxReqDto.getVin());
        if (oldVehicleBase == null && oldVehicleTbox == null) {
            RestResponse.failure("拒绝注册");
            //vehicleBaseAndVehicleTboxNotExist(vehicleTboxReqDto);
        } else if (oldVehicleBase == null && oldVehicleTbox != null) {
            //终端已授权。车辆不存在
            if (oldVehicleTbox.getAuthorizedStatus().intValue()==AuthorizedEnum.AUTHORIZED.getCode()){
                //生成 车辆未授权报警
                vehicleBaseNotExistVehicleTboxExist(oldVehicleTbox, vehicleTboxReqDto);
            }
        } else if (oldVehicleBase != null && oldVehicleTbox == null) {
            //车辆已授权。tbox不存在
            if (oldVehicleBase.getAuthorizedStatus().intValue()==AuthorizedEnum.AUTHORIZED.getCode()){
                vehicleTboxReqDto.setCompanyId(oldVehicleBase.getCompanyId());
                vehicleTboxReqDto.setCompanyName(oldVehicleBase.getCompanyName());
                vehicleBaseExistVehicleTboxNotExist(oldVehicleBase, vehicleTboxReqDto);
            }
        } else {
            if(oldVehicleTbox.getCompanyId().longValue()==oldVehicleBase.getCompanyId().longValue()){
                vehicleBaseExistVehicleTboxExist(oldVehicleTbox, oldVehicleBase, vehicleTboxReqDto);
            }else{
                return RestResponse.failure("车辆与终端公司不相同");
            }
        }
        //去重
        if (oldVehicleBase != null && oldVehicleTbox != null&&Objects.equals(oldVehicleBase.getVin(),oldVehicleTbox.getVin())){
            return RestResponse.success("注册成功");
        }
        //添加车辆注册日志；
        saveVehicleRegisterRecord(vehicleTboxReqDto, oldVehicleTbox, oldVehicleBase);
        return RestResponse.success("注册成功");
    }

    @Override
    public RestResponse<PageExtend<VehicleTboxResDto>> listVehicleTboxs(
            QueryVehicleTboxListParamDto queryParam) {
        log.info("车辆监控-车载终端-列表入参" + queryParam);
        ValidationUtils.validateBean(queryParam);
        try {
            //如果是企业用户
            if (UserTypeEnum.COMPANY.getFlag() == queryParam.getSysUserType().intValue()) {
                queryParam.setCompanyId(queryParam.getSysCompanyId());
            }
            IPage<VehicleTbox> listVehicleTboxs = iVehicleTboxService
                    .listVehicleTboxs(queryParam);
            if (CollectionUtils.isEmpty(listVehicleTboxs) || CollectionUtils.isEmpty(
                    listVehicleTboxs.getRecords())) {
                return RestResponse.success();
            }
            List<String> vin = listVehicleTboxs.getRecords().stream().map(VehicleTbox::getVin)
                    .collect(Collectors.toList());
            RestResponse<List<String>> onlineList = iRealService.isOnlineList(vin);
            ServiceValidation.validationService(onlineList, SysConstants.IOV_SERVICE_REAL);
            PageExtend<VehicleTboxResDto> list = new PageExtend<>();
            list.setPageSize(listVehicleTboxs.getSize());
            list.setTotal(listVehicleTboxs.getTotal());
            list.setPageNumber(listVehicleTboxs.getCurrent());

            List<VehicleTboxResDto> vehicleTboxResDtos = new ArrayList<>();
            for (VehicleTbox record : listVehicleTboxs.getRecords()) {
                VehicleTboxResDto vehicleTboxResDto = new VehicleTboxResDto();
                CommonUtils.copyProperties(record, vehicleTboxResDto);
                StringBuffer sb = new StringBuffer();
                //tbox 生产厂家
                sb.append(getDictValue(DictConstants.DICT_TYPE_TBOXN, record.getSupplierName()));
                sb.append("-");
                //tbox 型号terminalModelName
                sb.append(getDictValue(DictConstants.DICT_TYPE_TBOXM, record.getDeviceModel()));
                vehicleTboxResDto.setTerminalModelName(sb.toString().contains("null")?null:sb.toString());
                if (onlineList.getData() != null && !onlineList.getData().isEmpty()) {
                    if (onlineList.getData().contains(record.getVin())) {
                        vehicleTboxResDto.setOnLineStatus(OnLineStatusEnum.YES.getCode());
                        vehicleTboxResDto.setOnLineStr(OnLineStatusEnum.YES.getCnName());
                    } else {
                        vehicleTboxResDto.setOnLineStatus(OnLineStatusEnum.NO.getCode());
                        vehicleTboxResDto.setOnLineStr(OnLineStatusEnum.NO.getCnName());
                    }
                } else {
                    vehicleTboxResDto.setOnLineStatus(OnLineStatusEnum.NO.getCode());
                    vehicleTboxResDto.setOnLineStr(OnLineStatusEnum.NO.getCnName());
                }
                if (vehicleTboxResDto.getAuthorizedStatus()!=null&&vehicleTboxResDto.getAuthorizedStatus().intValue()==AuthorizedEnum.AUTHORIZED.getCode()){
                    vehicleTboxResDto.setAuthorizedStatusStr(AuthorizedEnum.AUTHORIZED.getName());
                }else{
                    vehicleTboxResDto.setAuthorizedStatusStr(AuthorizedEnum.UN_AUTHORIZED.getName());
                }
                vehicleTboxResDtos.add(vehicleTboxResDto);
            }
            list.setRecords(vehicleTboxResDtos);
            return RestResponse.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.failure(e.getMessage());
        }
    }

    @Override
    public RestResponse updateVehicleTbox(VehicleTboxUpdateReqDto dto) {
        log.info("车辆监控-车载终端-更改SIM卡入参" + dto);
        ValidationUtils.validateBean(dto);
        VehicleTbox bong = iVehicleTboxService.getVehicleTboxBySimNo(dto.getSimNo());
        if (!CollectionUtils.isEmpty(bong)) {
            return RestResponse.failure("SIM卡号已存在");
        }

        VehicleTbox tbox = iVehicleTboxService
            .getVehicleTboxByDeviceId(dto.getDeviceId());
        if (CollectionUtils.isEmpty(tbox)) {
            return RestResponse.failure("找不到Tbox");
        }

        VehicleSimChangeRecord simChangeRecord = new VehicleSimChangeRecord();
        VehicleTbox update = new VehicleTbox();
        CommonUtils.copyProperties(tbox, update);
        simChangeRecord.setOldSimNo(tbox.getSimNo());
        update.setSimNo(dto.getSimNo());
        update.setGmtModified(new Date());
        update.setModifiedUser(dto.getSysUserId().toString());
        boolean b = iVehicleTboxService.updateVehicleTbox(tbox, update);
        if (b) {
            //变更sim时，添加变更日志
            simChangeRecord.setSerialNumber(SnowflakeUtils.getId());
            CommonUtils.copyProperties(tbox, simChangeRecord);
            recordService.saveVehicleSimChangeRecord(simChangeRecord);
        }
        return RestResponse.success();
    }

    @Override
    public VehicleBaseTboxResDto getVehicleTboxByVin(String vin) {
        if (vin == null) {
            throw new BusinessException("车架号不能为空");
        }
        VehicleBaseTboxResDto vehicleTboxResDto = new VehicleBaseTboxResDto();
        VehicleTbox vehicleTboxByVin = iVehicleTboxService.getVehicleTboxByVin(vin);
        CommonUtils.copyProperties(vehicleTboxByVin, vehicleTboxResDto);
        VehicleBase vehicleBaseByVin = iVehicleBaseService.getVehicleBaseByVin(vin);
        CommonUtils.copyProperties(vehicleBaseByVin, vehicleTboxResDto);
        return vehicleTboxResDto;
    }

    /**
     * 添加终端注册日志
     *
     * @param vehicleTboxReqDto
     * @param oldVehicleTbox
     * @param oldVehicleBase
     */
    public void saveVehicleRegisterRecord(VehicleTboxReqDto vehicleTboxReqDto, VehicleTbox oldVehicleTbox, VehicleBase oldVehicleBase) {
        VehicleRegisterRecord record = new VehicleRegisterRecord();
        CommonUtils.copyProperties(vehicleTboxReqDto, record);
        record.setSerialNumber(SnowflakeUtils.getId());
        record.setRegisterTime(Calendar.getInstance().getTime());
        if (oldVehicleTbox != null) {
            StringBuffer sb = new StringBuffer();
            //tbox 生产厂家
            sb.append(getDictValue(DictConstants.DICT_TYPE_TBOXN, oldVehicleTbox.getSupplierName()));
            sb.append("-");
            //tbox 型号
            sb.append(getDictValue(DictConstants.DICT_TYPE_TBOXM, oldVehicleTbox.getDeviceModel()));
            record.setTerminalModelName(sb.toString().contains("null")?null:sb.toString());
            record.setTboxCompanyId(oldVehicleTbox.getCompanyId());
            record.setTboxCompanyName(oldVehicleTbox.getCompanyName());
        }
        if (oldVehicleBase != null) {
            record.setLicense(oldVehicleBase.getLicense());
            record.setVehicleCompanyId(oldVehicleBase.getCompanyId());
            record.setVehicleCompanyName(oldVehicleBase.getCompanyName());
        }
        vehicleRegisterRecordService.saveVehicleRegisterLog(record);
    }

    /**
     * 当 vehicleBaseAndVehicleTbox 都不在数据库里
     */
    public void vehicleBaseAndVehicleTboxNotExist(VehicleTboxReqDto vehicleTboxReqDto) {
        //添加车辆信息
         saveVehicleBase(vehicleTboxReqDto);
        //添加车联未授权报警
        saveUnauthorizedAlarmEquipmentRecord(vehicleTboxReqDto);
        //添加Tbox
        iVehicleTboxService.saveVehicleTbox(vehicleTboxReqDto);
    }

    /**
     * 当  vehicleBase  不存在    VehicleTbox存在
     */
    public void vehicleBaseNotExistVehicleTboxExist(VehicleTbox vehicleTbox,
                                                    VehicleTboxReqDto vehicleTboxReqDto) {
        Date date = Calendar.getInstance().getTime();
        if (vehicleTbox.getCompanyId() != null) {
            vehicleTboxReqDto.setCompanyId(vehicleTbox.getCompanyId());
            vehicleTboxReqDto.setCompanyName(vehicleTbox.getCompanyName());
        }
        //添加车辆信息
        saveVehicleBase(vehicleTboxReqDto);
        //添加车联未授权报警
        saveUnauthorizedAlarmEquipmentRecord(vehicleTboxReqDto);
        if (vehicleTbox != null && StringUtils.isNotBlank(vehicleTbox.getVin())) {
            //添加设备移除报警
            saveRemoveAlarmRecord(vehicleTbox);
            VehicleTbox old = iVehicleTboxService.getVehicleTboxByVin(vehicleTbox.getVin());
            if (old != null) {
                VehicleTbox update = new VehicleTbox();
                CommonUtils.copyProperties(old, update);
                update.setIccid(vehicleTboxReqDto.getIccid());
                update.setVin("");
                update.setGmtModified(date);
                iVehicleTboxService.updateVehicleTbox(old, update);
            }
          /*  //更新tbox信息
            VehicleTbox update = new VehicleTbox();
            CommonUtils.copyProperties(vehicleTbox, update);
            update.setVin(vehicleTboxReqDto.getVin());
            update.setIccid(vehicleTboxReqDto.getIccid());
            update.setGmtModified(date);
            iVehicleTboxService.updateVehicleTbox(vehicleTbox, update);*/
        }
        //添加终端安装审核
        saveTerminalInstallationAudit(vehicleTbox,vehicleTboxReqDto);

    }

    /**
     * 添加终端安装审核 3.10
     * @param vehicleTbox
     * @param vehicleTboxReqDto
     */
     private void  saveTerminalInstallationAudit(VehicleTbox vehicleTbox,
                                                 VehicleTboxReqDto vehicleTboxReqDto){
         Date date = Calendar.getInstance().getTime();
         TerminalInstallationAudit audit=new TerminalInstallationAudit();
         audit.setVin(vehicleTboxReqDto.getVin());
         audit.setDeviceId(vehicleTbox.getDeviceId());
         audit.setDeviceModel(vehicleTbox.getDeviceModel());
         audit.setIccid(vehicleTbox.getIccid());
         audit.setAuditStatus(AuditStatusEnum.NO.getCode());
         audit.setCompanyId(vehicleTbox.getCompanyId());
         audit.setCompanyName(vehicleTbox.getCompanyName());
         audit.setGmtCreate(date);
         audit.setRegisterTime(date);
         //生成安装审核记录
         iTerminalInstallationAuditService.save(audit);
     }

    /**
     * 当  vehicleBase  存在    VehicleTbox不存在存在 正常绑定
     */
    public void vehicleBaseExistVehicleTboxNotExist(VehicleBase oldVehicleBase, VehicleTboxReqDto vehicleTboxReqDto) {

        VehicleTbox oldTbox = iVehicleTboxService.getVehicleTboxByVin(oldVehicleBase.getVin());
        //添加  VehicleTbox 不添加vin
        RestResponse restResponse = iVehicleTboxService.saveVehicleTbox(vehicleTboxReqDto);
        if (!restResponse.isFlag()) {
            throw new BusinessException("注册tbox失败");
        }
        VehicleTbox newTbox = null;
        if (oldTbox != null) {
            //新tbox
             newTbox = iVehicleTboxService
                    .getVehicleTboxByDeviceId(vehicleTboxReqDto.getDeviceId());
            //设备拆除报警
            saveRemoveAlarmRecord(oldTbox);
            //设备更换报警
            saveChangeAlarmRecord(newTbox, oldTbox, oldVehicleBase);
            VehicleTbox update = new VehicleTbox();
            CommonUtils.copyProperties(oldTbox, update);
            update.setVin("");
            update.setGmtModified(new Date());
            iVehicleTboxService.updateVehicleTbox(oldTbox, update);
        }
        //添加终端安装审核
        saveTerminalInstallationAudit(newTbox,vehicleTboxReqDto);
    }

    /**
     * 当  vehicleBase  存在    VehicleTbox存在
     */
    public void vehicleBaseExistVehicleTboxExist(
            VehicleTbox oldVehicleTbox, VehicleBase oldVehicleBase,
            VehicleTboxReqDto vehicleTboxReqDto) {
        //只处理已授权的
        if (oldVehicleBase.getAuthorizedStatus().intValue()==AuthorizedEnum.AUTHORIZED.getCode()
        ){
            //排除已绑定
            if (!oldVehicleBase.getVin().equals(oldVehicleTbox.getVin())) {
                Date date = Calendar.getInstance().getTime();
                if (StringUtils.isNotBlank(oldVehicleTbox.getVin())) {
                    //添加设备移除报警
                    saveRemoveAlarmRecord(oldVehicleTbox);
                }
                VehicleTbox oldTbox = iVehicleTboxService
                        .getVehicleTboxByVin(oldVehicleBase.getVin());
                //设备更换报警
                saveChangeAlarmRecord(oldVehicleTbox, oldTbox, oldVehicleBase);
                //移除
                VehicleTbox old = iVehicleTboxService.getVehicleTboxByVin(oldVehicleBase.getVin());
                if (old != null) {
                    VehicleTbox update = new VehicleTbox();
                    CommonUtils.copyProperties(old, update);
                    update.setVin("");
                    update.setGmtModified(date);
                    iVehicleTboxService.updateVehicleTbox(old, update);
                }

                //更新tbox信息
                VehicleTbox update = new VehicleTbox();
                CommonUtils.copyProperties(oldVehicleTbox, update);
                update.setVin("");
                update.setIccid(vehicleTboxReqDto.getIccid());
                update.setGmtModified(date);
                //设置tbox公司 规则
                if (update.getCompanyId() == 0) {
                    VehicleBase vehicleBaseByVin = iVehicleBaseService
                            .getVehicleBaseByVin(vehicleTboxReqDto.getVin());
                    update.setCompanyId(vehicleBaseByVin.getCompanyId());
                    update.setCompanyName(vehicleBaseByVin.getCompanyName());
                }
                 iVehicleTboxService.updateVehicleTbox(oldVehicleTbox, update);
                //添加安装审核记录
                saveTerminalInstallationAudit(oldVehicleTbox,vehicleTboxReqDto);
            } else {
                if (!oldVehicleTbox.getIccid().equals(vehicleTboxReqDto.getIccid())) {
                    //更新tbox信息
                    VehicleTbox update = new VehicleTbox();
                    CommonUtils.copyProperties(oldVehicleTbox, update);
                    update.setIccid(vehicleTboxReqDto.getIccid());
                    update.setGmtModified(new Date());
                    iVehicleTboxService.updateVehicleTbox(oldVehicleTbox, update);
                }
            }
        }
    }

    /**
     * 发送报警邮件
     */
    @Async
    public void sendAlarmMessage(String vin, AlarmCodeEnum alarmCodeEnum) {
        NoticeMessageCenterDto noticeMessageCenterDto = new NoticeMessageCenterDto();
        noticeMessageCenterDto.setMessageSource(alarmCodeEnum.getFlag());
        noticeMessageCenterDto.setMessageType(MessageTypeEnum.ALARM.getMessageCode());
        noticeMessageCenterDto.setVin(vin);
        RestResponse trigger = noticeMessageCenterRemoteService.trigger(noticeMessageCenterDto);
        if (trigger == null) {
            log.info("服务调用失败");
        } else {
            log.info("发送" + alarmCodeEnum.getMsg() + "报警邮件:{}" + trigger.message);
        }

    }

    /**
     * 添加 设备更换报警 记录
     *
     * @param oldTbox 需要移除的tbox
     * @param newTbox 新的tbox
     */

    public void saveChangeAlarmRecord(VehicleTbox newTbox, VehicleTbox oldTbox, VehicleBase vehicleBase
    ) {
        Date time = Calendar.getInstance().getTime();
        AlarmEquipmentRecord alarmEquipmentRecord = new AlarmEquipmentRecord();
        alarmEquipmentRecord.setAlarmType(AlarmTypeEnum.EQUIPMENT_REPLACEMENT.getCode());
        String vin = "";
        if (vehicleBase != null) {
            alarmEquipmentRecord.setLicense(vehicleBase.getLicense());
            alarmEquipmentRecord.setVehicleModel(getVehicleModel(vehicleBase));
            alarmEquipmentRecord.setVin(vehicleBase.getVin());
            alarmEquipmentRecord.setCompanyId(vehicleBase.getCompanyId());
            alarmEquipmentRecord.setCompanyName(vehicleBase.getCompanyName());
            vin = vehicleBase.getVin();
        }
        alarmEquipmentRecord.setGmtCreate(time);
        alarmEquipmentRecord.setGmtModified(time);
        alarmEquipmentRecord.setHandlingStatus(HandlingStatusEnum.NO.getCode());
        alarmEquipmentRecord.setNewDeviceId(newTbox.getDeviceId());
        alarmEquipmentRecord.setNewIccid(newTbox.getIccid());
        if (oldTbox != null) {
            alarmEquipmentRecord.setOldDeviceId(oldTbox.getDeviceId());
            alarmEquipmentRecord.setOldRegisterTime(oldTbox.getRegisterTime());
            alarmEquipmentRecord.setOldIccid(oldTbox.getIccid());
            alarmEquipmentRecord.setOperationRemark(
                    "车辆" + vin + "绑定的T-Box由" + oldTbox.getDeviceId()
                            + "变更为" + newTbox
                            .getDeviceId());
        } else {
            alarmEquipmentRecord.setOperationRemark(
                    "车辆" + vin + "绑定的T-Box由"
                            + "变更为" + newTbox
                            .getDeviceId());
        }
        alarmEquipmentRecord.setAlarmId(SnowflakeUtils.getId());
        iAlarmEquipmentRecordService.saveAlarmEquipmentRecord(alarmEquipmentRecord);
        //发送邮件 设备更换报警
        sendAlarmMessage(vehicleBase.getVin(), AlarmCodeEnum.DEVICE_CHAGNGE);
    }

    /**
     * 添加 设备拆除报警 记录
     *
     * @param removeTbox 需要移除的tbox
     */
    public void saveRemoveAlarmRecord(VehicleTbox removeTbox) {
        VehicleBase vehicleBaseByVin = iVehicleBaseService.getVehicleBaseByVin(removeTbox.getVin());
        if (vehicleBaseByVin != null) {
            Date time = Calendar.getInstance().getTime();
            AlarmEquipmentRecord alarmEquipmentRecord = new AlarmEquipmentRecord();
            alarmEquipmentRecord.setAlarmType(AlarmTypeEnum.EQUIPMENT_REMOVAL.getCode());
            alarmEquipmentRecord.setOperationRemark(
                    "车辆" + removeTbox.getVin() + "绑定的T-Box由" + removeTbox.getDeviceId() + "变更为空");
            alarmEquipmentRecord.setGmtCreate(time);
            alarmEquipmentRecord.setGmtModified(time);
            alarmEquipmentRecord.setVin(removeTbox.getVin());
            alarmEquipmentRecord.setOldDeviceId(removeTbox.getDeviceId());
            alarmEquipmentRecord.setOldRegisterTime(removeTbox.getRegisterTime());

            if (vehicleBaseByVin != null) {
                alarmEquipmentRecord.setLicense(vehicleBaseByVin.getLicense());
                alarmEquipmentRecord.setVehicleModel(getVehicleModel(vehicleBaseByVin));
            }
            alarmEquipmentRecord.setHandlingStatus(HandlingStatusEnum.NO.getCode());
            alarmEquipmentRecord.setCompanyId(vehicleBaseByVin.getCompanyId());
            alarmEquipmentRecord.setCompanyName(vehicleBaseByVin.getCompanyName());
            alarmEquipmentRecord.setAlarmId(SnowflakeUtils.getId());
            iAlarmEquipmentRecordService.saveAlarmEquipmentRecord(alarmEquipmentRecord);
            //发送邮件 设备拆除报警
            sendAlarmMessage(vehicleBaseByVin.getVin(), AlarmCodeEnum.DEVICE_TEAR_DOWN);
        }
    }

    /**
     * 通过vin VehicleTbox VehicleBase
     */
    public VehicleBase getVehicleBaseByVin(String vin) {
        if (StringUtils.isBlank(vin)) {
            throw new BusinessException("vin：参数为空");
        }
        return iVehicleBaseService.getVehicleBaseByVin(vin);
    }

    /**
     * 通过deviceId VehicleTbox 获取VehicleTbox
     */

    @Override
    public VehicleTbox getVehicleTboxByDeviceId(String deviceId) {
        if (StringUtils.isBlank(deviceId)) {
            throw new BusinessException("deviceId：参数为空");
        }
        return iVehicleTboxService.getVehicleTboxByDeviceId(deviceId);
    }

    @Override
    public List<VehicleTbox> listVehicleTbox() {
        return iVehicleTboxService.listVehicleTbox();
    }

    @Override
    public RestResponse queryVehicleTboxCount() {
        return iVehicleTboxService.queryVehicleTboxCount();
    }

    @Override
    public RestResponse<List<VehicleTboxResDto>> listVehicleTboxList(List<String> vinList) {
        List<VehicleTbox> vehicleTboxList = iVehicleTboxService.listVehicleTboxList(vinList);
        List<VehicleTboxResDto> dtoList = new ArrayList<>();
        if (CollectionUtils.isEmpty(vehicleTboxList)) {
            return RestResponse.success();
        } else {
            vehicleTboxList.forEach(vehicleTbox -> {
                VehicleTboxResDto vehicleTboxResDto = new VehicleTboxResDto();
                CommonUtils.copyProperties(vehicleTbox, vehicleTboxResDto);
                dtoList.add(vehicleTboxResDto);
            });
            return RestResponse.success(dtoList);
        }
    }

    /**
     * 修改tbox
     *
     * @param dto
     * @return
     */
    @Override
    public RestResponse updateVehicleTbox(VehicleTboxReqDto dto) {
        log.info("车辆监控-车载终端-编辑-入参vehicleParam:{}", JsonUtils.toJson(dto));
        ValidationUtils.validateBean(dto, VehicleTboxReqDto.Update.class);
        Date time = Calendar.getInstance().getTime();
        VehicleTbox vehicleTbox = iVehicleTboxService.getVehicleTboxByDeviceId(dto.getDeviceId());
        if (vehicleTbox == null) {
            return RestResponse.failure("tbox不存在");
        }
        VehicleTbox iccid = iVehicleTboxService.getVehicleTboxByIccid(dto.getIccid());
        if (iccid != null&& !Objects.equals(vehicleTbox.getDeviceId(),iccid.getDeviceId() )) {
            return RestResponse.failure("ICCID已存在");
        }
        VehicleTbox newVehicleTbox = new VehicleTbox();
        CommonUtils.copyProperties(vehicleTbox, newVehicleTbox);
        CommonUtils.copyProperties(dto, newVehicleTbox);
        newVehicleTbox.setGmtModified(time);
        newVehicleTbox.setModifiedUser(dto.getSysUserId().toString());
        iVehicleTboxService.updateVehicleTbox(vehicleTbox, newVehicleTbox);
        return RestResponse.success();
    }

    @Override
    public RestResponse<PageExtend<VehicleTboxBindingResDto>> listVehicleTboxBinding(QueryVehicleTboxListParamDto queryParam) {
        log.info("设备管理-终端安装管理-有效授权列表入参" + queryParam);
        ValidationUtils.validateBean(queryParam);
            //如果是企业用户
        if (UserTypeEnum.COMPANY.getFlag() == queryParam.getSysUserType().intValue()) {
            queryParam.setCompanyId(queryParam.getSysCompanyId());
        }
            IPage<VehicleTbox> listVehicleTboxs = iVehicleTboxService
                    .listVehicleTboxBinding(queryParam);
            if (CollectionUtils.isEmpty(listVehicleTboxs) || CollectionUtils.isEmpty(
                    listVehicleTboxs.getRecords())) {
                return RestResponse.success();
            }
            PageExtend<VehicleTboxBindingResDto> list = new PageExtend<>();
            list.setPageSize(listVehicleTboxs.getSize());
            list.setTotal(listVehicleTboxs.getTotal());
            list.setPageNumber(listVehicleTboxs.getCurrent());
            List<VehicleTboxBindingResDto> vehicleTboxResDtos = new ArrayList<>();
            for (VehicleTbox record : listVehicleTboxs.getRecords()) {
                VehicleTboxBindingResDto vehicleTboxResDto = new VehicleTboxBindingResDto();
                CommonUtils.copyProperties(record, vehicleTboxResDto);
                vehicleTboxResDtos.add(vehicleTboxResDto);
            }
            list.setRecords(vehicleTboxResDtos);
            return RestResponse.success(list);

    }

    @Override
    public RestResponse listVehicleTboxBindingSave(TerminalBindingSaveDto dto) {
        log.info("设备管理-终端安装管理-有效授权-添加入参" + dto);
        ValidationUtils.validateBean(dto);
        //如果是企业用户
        if (UserTypeEnum.COMPANY.getFlag() == dto.getSysUserType().intValue()) {
            dto.setCompanyId(dto.getSysCompanyId());
        }
        if (dto.getCompanyId()==null){
         return    RestResponse.failure("未指定绑定企业");
        }
        VehicleBase vehicleBase = iVehicleBaseService.getVehicleBaseByVin(dto.getVin());
        if(vehicleBase==null||vehicleBase.getCompanyId().longValue()!=dto.getCompanyId().longValue()
                ||vehicleBase.getAuthorizedStatus().intValue()==AuthorizedEnum.UN_AUTHORIZED.getCode()){
            return    RestResponse.failure("添加失败，当前车辆不存在或未授权");
        }
        VehicleTbox oldVehicleTbox = iVehicleTboxService.getVehicleTboxByDeviceId(dto.getDeviceId());
        if (oldVehicleTbox==null||oldVehicleTbox.getCompanyId().longValue()!=dto.getCompanyId().longValue()){
            return    RestResponse.failure("添加失败，当前T-Box不存在或未授权");
        }
        if (StringUtils.isNotBlank(oldVehicleTbox.getVin())){
            return    RestResponse.failure("添加失败，车辆或T-Box存在其他授权");
        }
        //校验vin是否绑定tbox;
        VehicleTbox vehicleTboxByVin = iVehicleTboxService.getVehicleTboxByVin(dto.getVin());
        if (vehicleTboxByVin!=null){
            return    RestResponse.failure("添加失败，车辆或T-Box存在其他授权");
        }
        VehicleTbox tbox=new VehicleTbox();
        Date date=Calendar.getInstance().getTime();
        CommonUtils.copyProperties(oldVehicleTbox,tbox);
        tbox.setVin(dto.getVin());
        tbox.setModifiedRealName(dto.getSysRealName());
        tbox.setGmtModified(date);
        tbox.setRegisterTime(date);
        boolean b = iVehicleTboxService.updateVehicleTbox(oldVehicleTbox, tbox);
        if (b){
            saveTerminalInstallLogs(tbox,dto);
            return   RestResponse.success();
        }else {
            return   RestResponse.failure("添加失败");
        }

    }

    @Override
    public RestResponse listVehicleTboxBindingDelete(TerminalBindingDeleteDto dto) {
        ValidationUtils.validateBean(dto);

        VehicleTbox oldVehicleTbox = iVehicleTboxService.getVehicleTboxByDeviceId(dto.getDeviceId());
        if (oldVehicleTbox==null){
            return    RestResponse.failure("当前T-Box不存在");
        }
        //如果是企业用户只能修改自己的tbox
        if (UserTypeEnum.COMPANY.getFlag() == dto.getSysUserType().intValue()&&oldVehicleTbox.getCompanyId().longValue()!=dto.getSysCompanyId()) {
            return    RestResponse.failure("企业用户只能解绑自己的T-Box绑定关系");
        }
        VehicleTbox tbox=new VehicleTbox();
        Date date=Calendar.getInstance().getTime();
        CommonUtils.copyProperties(oldVehicleTbox,tbox);
        tbox.setVin("");
        tbox.setModifiedRealName(dto.getSysRealName());
        tbox.setGmtModified(date);
        boolean b = iVehicleTboxService.updateVehicleTbox(oldVehicleTbox, tbox);
        if(b){
            return RestResponse.success();
        }else{
            return RestResponse.failure("删除授权失败");
        }
    }

    @Override
    public RestResponse saveVehicleTbox(VehicleTboxReqDto dto) {
        ValidationUtils.validateBean(dto,VehicleTboxReqDto.Save.class);
        VehicleTbox vehicleTbox = iVehicleTboxService.getVehicleTboxByDeviceId(dto.getDeviceId());
        if(vehicleTbox!=null){
            return RestResponse.failure("终端已存在");
        }  //如果是企业用户只能修改自己的tbox
        VehicleTbox iccid = iVehicleTboxService.getVehicleTboxByIccid(dto.getIccid());
        if (iccid != null) {
            return RestResponse.failure("iccid已存在");
        }
        if (UserTypeEnum.COMPANY.getFlag() == dto.getSysUserType().intValue()) {
            dto.setCompanyId(dto.getSysCompanyId());
            dto.setCompanyName(dto.getCompanyName());
        }
        return iVehicleTboxService.saveVehicleTbox(dto);
    }

    /**
     * 添加安装日志
     *
     * @param tbox
     * @param dto
     */
    public void saveTerminalInstallLogs(VehicleTbox tbox, TerminalBindingSaveDto dto) {
        Date date = Calendar.getInstance().getTime();
        TerminalInstallLogs logs = new TerminalInstallLogs();
        logs.setAuthorizedResult(AuditResultsEnum.YES.getCode());
        logs.setAuthorizedResultStr(AuditResultsEnum.YES.getName());
        logs.setAuthorizedSource(AuthorizedSourceEnum.INITIATIVE.getCode());
        logs.setAuthorizedSourceStr(AuthorizedSourceEnum.INITIATIVE.getName());
        logs.setVin(tbox.getVin());
        logs.setDeviceId(tbox.getDeviceId());
        logs.setDeviceModel(tbox.getDeviceModel());
        logs.setCompanyId(tbox.getCompanyId());
        logs.setCompanyName(tbox.getCompanyName());
        logs.setCreateUserId(dto.getSysUserId());
        logs.setCreateRealName(dto.getSysRealName());
        logs.setSerialNumber(SnowflakeUtils.getId());
        logs.setIccid(tbox.getIccid());
        logs.setGmtCreate(date);
        logsService.saveTerminalInstallLogs(logs);
    }

    /**
     * 封装VehicleBaseReq数据
     */
    public RestResponse saveVehicleBase(VehicleTboxReqDto vehicleTboxReqDto) {
        Date time = Calendar.getInstance().getTime();
        VehicleBaseReqDto vehicleBaseReqDto = new VehicleBaseReqDto();
        //未授权
        vehicleBaseReqDto.setVin(vehicleTboxReqDto.getVin());
        vehicleBaseReqDto.setAuthorizedStatus(AuthorizedEnum.UN_AUTHORIZED.getCode());
        vehicleBaseReqDto.setIsDelete(YesOrNoEnum.NO.getCode());
        vehicleBaseReqDto.setCompanyId(vehicleTboxReqDto.getCompanyId());
        vehicleBaseReqDto.setCompanyName(vehicleTboxReqDto.getCompanyName());
        vehicleBaseReqDto.setGmtCreate(time);
        vehicleBaseReqDto.setGmtModified(time);
        return iVehicleBaseService.saveVehicleBase(vehicleBaseReqDto);
    }

    /**
     * 添加车联未授权报警
     */
    public void saveUnauthorizedAlarmEquipmentRecord(
            VehicleTboxReqDto vehicleTboxAddReqDto) {
        /**
         * 判断是否已生成未授权报警
         */
        boolean b = iAlarmEquipmentRecordService.hasAlarmEquipmentRecordByVin(vehicleTboxAddReqDto.getVin());
        if (!b){
            Date time = Calendar.getInstance().getTime();
            AlarmEquipmentRecord alarmEquipmentRecord = new AlarmEquipmentRecord();
            alarmEquipmentRecord.setVin(vehicleTboxAddReqDto.getVin());
            alarmEquipmentRecord.setAlarmType(AlarmTypeEnum.EQUIPMENT_UNAUTHORIZED.getCode());
            alarmEquipmentRecord.setNewIccid(vehicleTboxAddReqDto.getIccid());
            alarmEquipmentRecord.setNewDeviceId(vehicleTboxAddReqDto.getDeviceId());
            alarmEquipmentRecord.setGmtCreate(time);
            alarmEquipmentRecord.setGmtModified(time);
            alarmEquipmentRecord.setHandlingStatus(HandlingStatusEnum.NO.getCode());
            alarmEquipmentRecord.setOperationRemark("车辆" + vehicleTboxAddReqDto.getVin() + "未授权");
            alarmEquipmentRecord.setAlarmId(SnowflakeUtils.getId());
            alarmEquipmentRecord.setCompanyId(vehicleTboxAddReqDto.getCompanyId());
            alarmEquipmentRecord.setCompanyName(vehicleTboxAddReqDto.getCompanyName());
            iAlarmEquipmentRecordService.saveAlarmEquipmentRecord(alarmEquipmentRecord);
            //发送邮件 设备更换报警
        }
    }

    /**
     * 返回车辆型号
     */
    public String getVehicleModel(VehicleBase vehicleBase) {
        if (vehicleBase != null &&
                vehicleBase.getBrand() != null &&
                vehicleBase.getVehicleSeries() != null &&
                vehicleBase.getVehicleType() != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(getDictValue(DictConstants.DICT_TYPE_VEHICLE_BRAND, vehicleBase.getBrand()));
            sb.append(getDictValue(DictConstants.DICT_TYPE_VEHICLE_BRAND_SERIES,
                    vehicleBase.getVehicleSeries()));
            sb.append(getDictValue(DictConstants.DICT_TYPE_VEHICLE_TYPE, vehicleBase.getVehicleType()));

            return sb.toString().contains("null")?null:sb.toString();
        } else {
            return null;
        }
    }

    /**
     * 获得
     */
    public String getDictValue(String dictType, String dictCode) {
        QueryWrapper<DictData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code", dictCode);
        queryWrapper.eq("dict_type", dictType);
        DictData one = dictDataService.getOne(queryWrapper);
        if (one != null) {
            return one.getDictValue();
        }
        return null;

    }
}
